package com.ys.otms.services.impl;

import com.ys.otms.constant.WxConstant;
import com.ys.otms.dao.IUserDao;
import com.ys.otms.dto.ParamDto;
import com.ys.otms.dto.UserDto;
import com.ys.otms.services.IDeductionsServices;
import com.ys.otms.services.IUserServices;
import com.ys.otms.utils.*;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements IUserServices {

    private static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private IUserDao iUserDao;

    @Autowired
    private IDeductionsServices iDeductionsServices;

    @Override
    public JSONObject queryUser(HttpServletRequest request) throws Exception {
        Integer userId = Integer.parseInt((String) request.getSession().getAttribute("SESSION_USER_ID"));
        UserDto dto = new UserDto();
        dto.setId(userId);
        List<UserDto> userDtoList = iUserDao.queryUser(dto);
        dto = userDtoList.get(0);
        JSONObject retObj = new JSONObject();
        retObj.put("userName",dto.getAccount());
        retObj.put("roleName",dto.getRoleName());
        retObj.put("phoneNum",dto.getPhoneNum());
        retObj.put("SUCCESS",true);
        return retObj;
    }

    @Override
    public JSONObject editPassword(HttpServletRequest request) throws Exception {
        JSONObject obj = JsonUtil.getJSONObject(request);
        logger.info("UserServiceImpl queryUser start obj:{}", obj);
        String oldPassword = JsonUtil.getJSONObjectString2(obj,"oldPassword");
        String newPassword = JsonUtil.getJSONObjectString2(obj,"newPassword");
        Integer userId = Integer.parseInt((String) request.getSession().getAttribute("SESSION_USER_ID"));
        UserDto dto = new UserDto();
        dto.setId(userId);
        dto.setPassword(oldPassword);
        List<UserDto> userDtoList = iUserDao.queryUser(dto);
        JSONObject retObj = new JSONObject();
        if (ListUtil.isEmpty(userDtoList)) {
            retObj.put("SUCCESS",false);
            retObj.put("MSG","原密码错误!");
            return retObj;
        }
        dto = userDtoList.get(0);
        dto.setPassword(newPassword);
        iUserDao.updateUser(dto);
        retObj.put("SUCCESS",true);
        retObj.put("MSG","修改成功!");
        return retObj;
    }

    @Override
    @Transactional
    public JSONObject addUser(HttpServletRequest request) throws Exception {
        JSONObject obj = JsonUtil.getJSONObject(request);
        logger.info("UserServiceImpl addUser obj:{}", obj);
        String isManager = (String) request.getSession().getAttribute("SESSION_IS_MANAGER");
        JSONObject retObj = new JSONObject();
        if ("N".equals(isManager)) {
            retObj.put("SUCCESS",false);
            retObj.put("MSG","没有权限!");
            return retObj;
        }
        String account = JsonUtil.getJSONObjectString(obj, "account");
		String password = JsonUtil.getJSONObjectString(obj, "password");
        String phoneNum = JsonUtil.getJSONObjectString(obj, "phoneNum");
        String roleId = JsonUtil.getJSONObjectString(obj, "roleId");

        if (StringUtil.isEmpty(account) || StringUtil.isEmpty(phoneNum)
                || StringUtil.isEmpty(password) || StringUtil.isEmpty(roleId)) {
            retObj.put("SUCCESS",false);
            retObj.put("MSG","请填写相关信息!");
            return retObj;
        }
        Integer userId = Integer.parseInt((String) request.getSession().getAttribute("SESSION_USER_ID"));
        String companyId = (String) request.getSession().getAttribute("SESSION_COMPANY_ID");

        UserDto user = new UserDto();
        user.setAccount(account);
        if(iUserDao.queryUser(user).size() > 0) {
            retObj.put("SUCCESS",false);
            retObj.put("MSG","用户名已存在!");
            return retObj;
        }
        user = new UserDto();
        user.setPhoneNum(phoneNum);
        if(iUserDao.queryUser(user).size() > 0) {
            retObj.put("SUCCESS",false);
            retObj.put("MSG","手机号已存在!");
            return retObj;
        }

        user = new UserDto();
        user.setAccount(account);
        user.setPassword(password);
        user.setPhoneNum(phoneNum);
        user.setParentId(userId);
        user.setCompany(companyId);
        user.setStatus(0);
        user.setIsBasic("Y");
        iUserDao.insertUser(user);

        user.setRoleId(Integer.parseInt(roleId));
        iUserDao.insertUserRole(user);

        //调用扣费逻辑
//        String consumeId = JsonUtil.getJSONObjectString(obj,"consumeId");
//
//        JSONObject reqObj = new JSONObject();
//        reqObj.put("consumeId", consumeId);
//        JSONArray shipList = new JSONArray();
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("shipId","test");
//        shipList.add(jsonObject);
//        reqObj.put("shipList", shipList);
//        JSONObject ret = iDeductionsServices.deductionsMethod(request, reqObj);
//        if(!ret.getBoolean("SUCCESS")) {
//            throw new RuntimeException(ret.getString("MSG"));
//        }

        retObj.put("SUCCESS",true);
        retObj.put("MSG","添加成功!");
        return retObj;
    }

    @Override
    public JSONObject editUser(HttpServletRequest request) throws Exception {
        JSONObject obj = JsonUtil.getJSONObject(request);
        logger.info("UserServiceImpl editUser obj:{}", obj);
        String isManager = (String) request.getSession().getAttribute("SESSION_IS_MANAGER");
        JSONObject retObj = new JSONObject();
        if ("N".equals(isManager)) {
            retObj.put("SUCCESS",false);
            retObj.put("MSG","没有权限!");
            return retObj;
        }

        String userId = JsonUtil.getJSONObjectString(obj, "userId");
        String account = JsonUtil.getJSONObjectString(obj, "account");
//        String phoneNum = JsonUtil.getJSONObjectString(obj, "phoneNum");
        UserDto userDto = new UserDto();
        userDto.setId(Integer.parseInt(userId));
        if (1 == iUserDao.queryUser(userDto).get(0).getRoleId()) {
            retObj.put("SUCCESS",false);
            retObj.put("MSG","修改失败，系统管理员不能修改!");
            return retObj;
        }
        userDto.setAccount(account);
//        userDto.setPhoneNum(phoneNum);
        iUserDao.updateUser(userDto);

        String roleId = JsonUtil.getJSONObjectString(obj, "roleId");
        if (StringUtil.isNotEmpty(roleId)) {
            if (!",2,3,".contains(roleId)) {
                retObj.put("SUCCESS",false);
                retObj.put("MSG","不存在该角色");
                return retObj;
            }
            userDto.setRoleId(Integer.parseInt(roleId));
            iUserDao.deleteUserRole(userDto);
            iUserDao.insertUserRole(userDto);
        }
        retObj.put("SUCCESS",true);
        retObj.put("MSG","修改成功!");
        return retObj;
    }

    @Override
    public JSONObject deleteUser(HttpServletRequest request) throws Exception {
        JSONObject obj = JsonUtil.getJSONObject(request);
        logger.info("UserServiceImpl deleteUser obj:{}", obj);
        String isManager = (String) request.getSession().getAttribute("SESSION_IS_MANAGER");
        JSONObject retObj = new JSONObject();
        if ("N".equals(isManager)) {
            retObj.put("SUCCESS",false);
            retObj.put("MSG","没有权限!");
            return retObj;
        }
        String userId = JsonUtil.getJSONObjectString(obj, "userId");
        UserDto userDto = new UserDto();
        userDto.setId(Integer.parseInt(userId));
        if (1 == iUserDao.queryUser(userDto).get(0).getRoleId()) {
            retObj.put("SUCCESS",false);
            retObj.put("MSG","删除失败，系统管理员不能删除!");
            return retObj;
        }
        iUserDao.deleteUserRole(userDto);
        iUserDao.deleteUser(userDto);

        retObj.put("SUCCESS",true);
        retObj.put("MSG","删除成功!");
        return retObj;
    }

    @Override
    public Map<String, Object> queryAllCompanyUser(HttpServletRequest request,String page, String limit) throws Exception {
        int companyId = Integer.parseInt((String) request.getSession().getAttribute("SESSION_COMPANY_ID"));

        ParamDto paramDto = new ParamDto();
        paramDto.setCompanyId(companyId);
        PageUtil.setPage(Integer.parseInt(page),Integer.parseInt(limit), paramDto);

        List<UserDto> list = iUserDao.queryAllCompanyUser(paramDto);
        Map<String, Object> result = new HashMap<>();
        result.put("data",list);
        result.put("SUCCESS",true);
        result.put("count", iUserDao.queryAllCompanyUserCount(paramDto));
        return result;
    }

    @Override
    public ModelAndView wxBindCallback(HttpServletRequest request) throws Exception{
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        logger.info("wxBindCallback code:{},state:{}", code, state);
        ModelAndView modelAndView = new ModelAndView();
        JSONObject retObj = new JSONObject();
        if(StringUtil.isEmpty(code)) {
            modelAndView.addObject("SUCCESS",false);
            modelAndView.addObject("MSG","用户禁止授权！");
            return modelAndView;
        }

        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
        url = url.replaceAll("APPID", WxConstant.APP_ID).replaceAll("SECRET", WxConstant.APP_SECRET).replaceAll("CODE", code);
        JSONObject jsonObject = HttpUtil.get(url);
        String openId = JsonUtil.getJSONObjectString(jsonObject, "openid");
        String unionId = JsonUtil.getJSONObjectString(jsonObject, "unionid");
        logger.info("LoginServiceImpl wxBindCallback start jsonObject:{}", jsonObject);
        if (StringUtil.isEmpty(unionId)) {
            String errCode = jsonObject.getString("errcode");
            String errMsg = jsonObject.getString("errmsg");
            logger.error("loginCallBack fail get Open Id errCode:{},errMsg:{}", errCode, errMsg);
            modelAndView.addObject("SUCCESS",false);
            modelAndView.addObject("MSG","获取unionId出错！");
            return modelAndView;
        }

        String deState = EncryptionUtil.jdkBase64Decode(state);
        String[] deStateArr = deState.split("&");
        String userId = deStateArr[0];
        String phoneNum = deStateArr[1];
        UserDto userDto = new UserDto();
        userDto.setId(Integer.parseInt(userId));
        userDto.setPhoneNum(phoneNum);
        List<UserDto> userDtoList = iUserDao.queryUser(userDto);
        logger.info("LoginServiceImpl wxBindCallback start userDtoList:{}",userDtoList);
        if (ListUtil.isEmpty(userDtoList)) {
            modelAndView.addObject("SUCCESS",false);
            modelAndView.addObject("MSG","state错误！");
            return modelAndView;
        }
        else {
            UserDto dto = userDtoList.get(0);
            dto.setUnionId(unionId);
            dto.setWxOpenId(openId);
            iUserDao.updateUser(dto);
            request.getSession().setAttribute("SESSION_WX_BIND","Y");

            modelAndView.addObject("SUCCESS",true);
            modelAndView.addObject("MSG","已经绑定！");
        }

        return modelAndView;
    }


}
